package cn.kgc.ssm.service.impl;

import cn.kgc.ssm.commons.ResponseResult;
import cn.kgc.ssm.entity.Course;
import cn.kgc.ssm.mapper.CourseMapper;
import cn.kgc.ssm.service.CourseService;
import cn.kgc.ssm.vo.CourseVO;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/5/18
 * @description
 */
@Service
@Transactional  // 开启事务管理
public class CourseServiceImpl implements CourseService {

    @Resource
    private CourseMapper courseMapper;


    @Override
    public ResponseResult coursePage(Integer page, Integer limit, String courseName) {

        PageHelper.startPage(page,limit);
        List<CourseVO>  courseVOS = courseMapper.selectCourseList(courseName);

        PageInfo<CourseVO> courseVOPageInfo = new PageInfo<>(courseVOS);
        long total = courseVOPageInfo.getTotal();
        return ResponseResult.success().data(courseVOS).count(total);
    }

    @Override
    public ResponseResult addUploadInfo(Course course) {

        courseMapper.insertCourseInfo(course);

        return ResponseResult.success().message("课程添加成功");
    }

    @Override
    public ResponseResult getCourseById(Integer id) {

         Course course =   courseMapper.selectCourseById(id);
        return ResponseResult.success().data(course);
    }

    @Override
    public ResponseResult editCourse(Course course) {

        long id  = course.getId();
        Integer IntId= Integer.valueOf(id + "");

        Course course1 = courseMapper.selectCourseById(IntId);
        String DBImg = course1.getImg();
        String formImg = course.getImg();

        if (!StringUtils.equals(DBImg,formImg)){
            // TODO 项目开发完毕之后   部署服务器之前需要更改此处的路径
            File file = new File("D:/upload/course/" + DBImg);
            file.delete();
        }
        courseMapper.updateCourseById(course);
        return ResponseResult.success().message("课程更新成功");
    }

    @Override
    public ResponseResult removeCourse(Integer id, String uuid) {

        courseMapper.deleteById(id);

        // 删除本地目录下的图片下信息
        // TODO   项目发布时 需要更改此处路径
        File file = new File("D:/upload/course/" + uuid);
        file.delete();

        return ResponseResult.success().message("课程信息删除成功");
    }

}
